package com.woohua.demo.controller;

import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @version 1.0
 * @author: woo hua
 * @DATE 2022/9/1 10:55
 * @description:
 */
@Slf4j
@Controller
public class LoginController {

    @Autowired
    private Producer kaptchaProducer;

    @RequestMapping(path = "/kaptcha", method = RequestMethod.GET)
    public void getKaptcha(HttpServletResponse response, HttpSession session) {
        // 生成验证码
        String text = kaptchaProducer.createText();
        // 将验证码传入生成图片
        BufferedImage image = kaptchaProducer.createImage(text);

        // 将验证码存入session
        session.setAttribute("kaptcha", text);

        // 将图片输出给浏览器
        // 声明返回给浏览器的是什么可视的数据
        response.setContentType("img/png");
        // response 向浏览器做响应我们需要获取它的输出流
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            // 这个流不用关，因为是SpringMVC维护，会自动关
            // 输出哪个图片，图片格式，哪个流输出
            ImageIO.write(image, "png", outputStream);
        } catch (IOException e) {
            log.error("响应验证码失败：{}", e.getMessage());
        }

    }

}
